import os
import sys

path = os.path.dirname(__file__)
sys.path.append(os.path.join(path, '..'))

import pymongo
from conf.config import MONGO_CONFIG


class MongoDbConnection(object):
    mongo_host = MONGO_CONFIG.get('host')
    mongo_port = MONGO_CONFIG.get('port')
    dbs = {}

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(MongoDbConnection, cls).__new__(cls)
        return cls._instance

    def __init__(self, db_name: str = ''):
        try:
            if db_name not in self.dbs:
                self.dbs[db_name] = self.client[db_name]
        except (Exception,) as e:
            raise ValueError(e)
        else:
            self._db = self.dbs[db_name]

    @property
    def client(self):
        return pymongo.MongoClient(f'mongodb://{self.mongo_host}:{self.mongo_port}/')

    @property
    def db(self):
        return self._db


BASIC_DATA_DB = MongoDbConnection(db_name='basic_data').db
